/**
 * 股价活跃度 GJHY 众赢投顾 副图指标
 */

import { movingAverage } from './MA'
import * as zytgTools from './ZYTG_UTIL'

const GJHY_HIGH_LOW_DAYS = 3              //最高价与最低价的统计天数
const GJHY_PRICE_DROP_INDEX = 0.5         //没有收阳时的取值系数
const GJHY_COMPARE_DAYS = 60              //默认价格比较天数
const GJHY_ARROW_COLOR_FOR_RAISING = 'red'      //上升箭头颜色 
const GJHY_ARROW_COLOR_FOR_DROPING = 'green'    //下降箭头颜色 
const GJHY_ARROW_STYLE_FOR_RAISING = 'up_arrow'      //上升箭头标识 
const GJHY_ARROW_STYLE_FOR_DROPING = 'down_arrow'    //下降箭头标识 

let initParam = {
  name: 'GJHY',
  type: 'polyline',
  caculateParam: [60],  // 默认用
}

/**
 * Caculator 数据处理
 *
 */
/**
 * Caculator 数据处理
 * @param  {array} rawData
 * @param  {array} caculateParam
 * @param  {int} dataSliceCount //额外前置增补数据数量 
 * @return {}
 *
 * 使用说明（render.k.chart.js CaclGJHY）：
 *
 * 数据结构说明（从GJHY开始统一所有指标的结构体）
  {
    "info": {id: "GJHY", title: "股价活跃度"},
    "curves": [
        {title: '活跃度', curve: [1.86, 1.705, 1.7867], color: ['blue']},
    ],
    "icons": [
      {icon: "up_arrow", time: "2017-02-13", color: "red", x: 82, y: 0.656}
    ],
    "rects": [],
    "lines": []
  }
 */
function caculate (rawData, caculateParam, dataSliceCount, summary) {
  console.log("GJHY raw data count", rawData.length)

  if (!(rawData instanceof Array)) throw new Error('Data or caculateParam is not Array')
  let period = (caculateParam instanceof Array) ? caculateParam[0] : GJHY_COMPARE_DAYS
  let mathData = _caculator(rawData, period, dataSliceCount, summary)
  return mathData
}

function _caculator (rawData, period, dataSliceCount, summary) {
  let sttRows = [];
  let arrows = []; 
  let high3Days = zytgTools.calcMaxMinOfDays(rawData, 'high', 3, zytgTools.MMD_GET_MAX)
  let low3Days = zytgTools.calcMaxMinOfDays(rawData, 'low', 3, zytgTools.MMD_GET_MIN)
  let maArray = zytgTools.calcMAByFields(rawData, [
          {field: "close", period: "60"}
      ])
  for (let i = dataSliceCount; i < rawData.length; i++) {
    let day = rawData[i];
    //获取三天的最高价减去三天的最低价
    let st = high3Days[i] - low3Days[i]

    //如果收阳，就取值st，如果没有收阳就取值st*0.5
    let stt = (day['close'] > day['open']) ? st : st * GJHY_PRICE_DROP_INDEX
    stt = {
      "time": day['time'],
      "value": parseFloat(stt.toFixed(2)),
      "periods": period      
    }
    // console.log(i, day, high3Days[i], low3Days[i], st, stt)
    sttRows.push(stt)

    //在上市后前60日不标注
    let issuePastDays = zytgTools.calcPastDays(summary.issue_date, rawData[i].time)
    let isDownArrow = (issuePastDays > 60)
    let isUpArrow = (issuePastDays > 60)

    if (isDownArrow || isUpArrow) {
      //获取60天内两组max/min计算值
      let currentA = day['close'] / day['high']   //收盘价除以最高价
      let currentB = day['close'] / day['low']    //收盘价除以最低价
      let periodStart = i - period + 1
      if (periodStart < 0) periodStart = 0
      for (let j = periodStart ; j < i; j++) {
        let tempA = rawData[j]['close'] / rawData[j]['high']   //收盘价除以最高价
        let tempB = rawData[j]['close'] / rawData[j]['low']    //收盘价除以最低价
        //当收盘价除以最高价是60天内的最小值
        if (tempA < currentA) {
          isDownArrow = false
        }
        //收盘价除以最低价是60天内的最大值
        if (tempB > currentB) {
          isUpArrow = false
        }
        if (!isDownArrow && !isUpArrow) {
          break;
        }
      }
    }

    //并且收盘在60日均线之上时，标绿色倒三角
    isDownArrow = isDownArrow && (day['close'] > maArray.close60[i])
    //并收盘小于60日均线，收阳，红色正三角
    isUpArrow = isUpArrow && (day['close'] < maArray.close60[i]) && (day['close'] > day['open'])

    if (isDownArrow) {
      arrows.push({
        time: day['time'],
        icon: GJHY_ARROW_STYLE_FOR_DROPING,
        color: GJHY_ARROW_COLOR_FOR_DROPING,
        x: i - dataSliceCount
      })
    }
    if (isUpArrow) {
      arrows.push({
        time: day['time'],
        icon: GJHY_ARROW_STYLE_FOR_RAISING,
        color: GJHY_ARROW_COLOR_FOR_RAISING,
        x: i - dataSliceCount
      })
    }
  }
  
  let result = {
    info: {id: "GJHY", title: "股价活跃度"},
    curves: [],
    icons: null
  }

  //输出十天的stt的移动平均线
  let sttMAArr = [];
  sttRows.forEach((d) => {
    sttMAArr.push(d.value)
  })
  sttMAArr = movingAverage(sttMAArr, 10)
  sttRows.forEach((d,i)=>{
    d.value = sttMAArr[i]
  })
  let sttMA10 = sttRows

  result.curves.push({
    title: '活跃度',
    color: 'blue',
    curve: sttMA10
  })
  //补充箭头纵坐标
  for (let i = 0; i < arrows.length; i++) {
    arrows[i].y = sttMA10[arrows[i].x].value
  }
  result.icons = arrows
  return result
  console.log(result)
}


export default {
  initParam: initParam,
  caculate: caculate
}
